import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import type { $Keys } from "utility-types";

/** 页面参数 */
export const useQuery = <
  P extends {
    [key: string]: unknown;
  },
  K extends $Keys<P> = $Keys<P>,
>(
  keys: K[],
  resolveConfig?: {
    [key in K]?: (value?: string) => P[key];
  },
) => {
  const params = ref({} as unknown as P);

  onLoad((query) => {
    console.log("useQuery onLoad");
    if (query) {
      keys.forEach((key) => {
        const value = (query as Record<K, string>)[key];
        const handler = resolveConfig?.[key] || ((value) => value);

        // @ts-ignore
        params.value[key] = handler(value);
      });
    }
  });

  return {
    params,
  };
};
